import React, { useState, useEffect } from "react";
import Box from "../../components/Box";
import Text from "../../components/Text";
import List from "../../components/List";
import SEO from "../../components/SEO";
import { getMagicPoints, getMagicHistory, addMagicPoints, hasCheckedInToday, getMonthlyCheckins, getMonthlyCheckinStatus, getLastDayOfMonth } from "../../components/UserMagic";
import Button from "../../components/Button";
import { NotificationContext } from "../../components/Notifications";
import { useContext } from "react";
import { CheckCircle, XCircle } from "@styled-icons/boxicons-regular";

const Magic = () => {
  const [magicValue, setMagicValue] = useState(0);
  const [history, setHistory] = useState([]);
  const [loading, setLoading] = useState(true);
  const [checkinStatus, setCheckinStatus] = useState({
    total: 0,
    completed: 0,
    remaining: 0,
    isComplete: false,
    bonusClaimed: false
  });
  const [monthlyCheckins, setMonthlyCheckins] = useState([]);
  
  const { addNotification } = useContext(NotificationContext);

  // 获取魔力值和历史记录
  useEffect(() => {
    const fetchMagicData = () => {
      try {
        setLoading(true);

        // 从localStorage获取魔力值
        const magic = getMagicPoints();
        setMagicValue(magic);
        
        // 从localStorage获取历史记录
        const historyData = getMagicHistory();
        setHistory(historyData);
        
        // 获取当月签到状态
        const status = getMonthlyCheckinStatus();
        setCheckinStatus(status);
        
        // 获取当月签到记录
        const checkins = getMonthlyCheckins();
        setMonthlyCheckins(checkins);
      } catch (error) {
        console.error("获取魔力值数据失败:", error);
      } finally {
        setLoading(false);
      }
    };

    fetchMagicData();
    
    // 添加事件监听器，当localStorage变化时更新
    const handleStorageChange = () => {
      fetchMagicData();
    };
    
    window.addEventListener('storage', handleStorageChange);
    
    return () => {
      window.removeEventListener('storage', handleStorageChange);
    };
  }, []);
  
  // 每日签到功能
  const handleDailyCheckIn = () => {
    // 检查今天是否已经签到
    if (hasCheckedInToday()) {
      addNotification("warning", "今天已经签到过了，明天再来吧！");
      return;
    }
    
    // 获取当前日期
    const today = new Date();
    const year = today.getFullYear();
    const month = today.getMonth() + 1;
    const day = today.getDate();
    
    // 当月签到记录的key
    const recordKey = `check_in_record_${year}_${month}`;
    
    // 获取当月签到记录
    let monthRecord = localStorage.getItem(recordKey);
    if (!monthRecord) {
      monthRecord = [];
    } else {
      monthRecord = JSON.parse(monthRecord);
    }
    
    // 如果今天还没签到，则添加签到记录
    if (!monthRecord.includes(day)) {
      monthRecord.push(day);
      localStorage.setItem(recordKey, JSON.stringify(monthRecord));
    }
    
    // 记录本次签到
    localStorage.setItem('last_check_in_date', today.toLocaleDateString());
    
    // 签到奖励50魔力值
    const newPoints = addMagicPoints(50, "每日签到");
    setMagicValue(newPoints);
    
    // 更新签到状态
    const status = getMonthlyCheckinStatus();
    setCheckinStatus(status);
    setMonthlyCheckins(monthRecord);
    
    // 检查月度全勤
    checkMonthlyBonus();
    
    // 更新历史记录
    setHistory(getMagicHistory());
    
    addNotification("success", "签到成功！获得50点魔力值");
  };
  
  // 检查月度全勤并奖励
  const checkMonthlyBonus = () => {
    const today = new Date();
    const year = today.getFullYear();
    const month = today.getMonth() + 1;
    
    // 获取当月签到记录
    const status = getMonthlyCheckinStatus();
    
    // 如果已经达到全勤条件且未领取奖励
    if (status.isComplete && !status.bonusClaimed) {
      // 增加500点月度全勤奖励
      addMagicPoints(500, `${year}年${month}月全勤奖励`);
      
      // 标记已领取全勤奖励
      localStorage.setItem(`monthly_bonus_${year}_${month}`, 'claimed');
      
      addNotification("success", `恭喜完成${year}年${month}月全勤！获得500点魔力值奖励`);
    }
  };
  
  // 领取月度全勤奖励
  const claimMonthlyBonus = () => {
    const today = new Date();
    const year = today.getFullYear();
    const month = today.getMonth() + 1;
    
    // 再次检查是否满足全勤条件且未领取奖励
    const status = getMonthlyCheckinStatus();
    if (!status.isComplete) {
      addNotification("error", "月度签到未达到全勤条件，无法领取奖励");
      return;
    }
    
    if (status.bonusClaimed) {
      addNotification("warning", "您已经领取过本月全勤奖励了");
      return;
    }
    
    // 增加500点月度全勤奖励
    addMagicPoints(500, `${year}年${month}月全勤奖励`);
    
    // 标记已领取全勤奖励
    localStorage.setItem(`monthly_bonus_${year}_${month}`, 'claimed');
    
    // 更新状态
    setCheckinStatus({...status, bonusClaimed: true});
    setMagicValue(getMagicPoints());
    setHistory(getMagicHistory());
    
    addNotification("success", `恭喜完成${year}年${month}月全勤！获得500点魔力值奖励`);
  };
  
  // 生成月历
  const renderCalendar = () => {
    const today = new Date();
    const year = today.getFullYear();
    const month = today.getMonth();
    
    // 获取当月第一天是星期几
    const firstDay = new Date(year, month, 1).getDay();
    
    // 获取当月总天数
    const daysInMonth = getLastDayOfMonth(today);
    
    // 建立日历数组
    const calendar = [];
    
    // 填充头部空白
    for (let i = 0; i < firstDay; i++) {
      calendar.push(null);
    }
    
    // 填充日期
    for (let i = 1; i <= daysInMonth; i++) {
      calendar.push(i);
    }
    
    return (
      <Box 
        display="grid" 
        gridTemplateColumns="repeat(7, 1fr)" 
        gap={2}
        mt={3}
      >
        {/* 星期头部 */}
        {['日', '一', '二', '三', '四', '五', '六'].map(day => (
          <Box 
            key={day} 
            textAlign="center" 
            py={1}
            fontSize={1}
            fontWeight="bold"
          >
            {day}
          </Box>
        ))}
        
        {/* 日历格子 */}
        {calendar.map((day, index) => (
          <Box 
            key={index}
            py={2}
            px={1}
            bg={day ? "sidebar" : "transparent"}
            borderRadius={2}
            textAlign="center"
            position="relative"
            opacity={day ? 1 : 0}
          >
            {day && (
              <>
                <Text fontSize={1}>{day}</Text>
                {monthlyCheckins.includes(day) && (
                  <Box 
                    position="absolute" 
                    top={0} 
                    right={0}
                    width="10px"
                    height="10px"
                    borderRadius="50%"
                    bg="success"
                  />
                )}
              </>
            )}
          </Box>
        ))}
      </Box>
    );
  };

  if (loading) {
    return (
      <>
        <SEO title="魔力值" />
        <Text as="h1" mb={5}>魔力值</Text>
        <Box p={4}>加载中...</Box>
      </>
    );
  }

  return (
    <>
      <SEO title="魔力值" />
      <Text as="h1" mb={5}>
        魔力值
      </Text>
      
      <Box
        display="flex"
        flexWrap="wrap"
        mb={5}
      >
        <Box
          flex="1"
          minWidth="250px"
          bg="sidebar"
          borderRadius={2}
          p={4}
          mb={[4, 0]}
          mr={[0, 4]}
        >
          <Text fontSize={2} fontWeight="bold" mb={3}>
            当前魔力值
          </Text>
          <Text fontSize={5} fontWeight="bold" color="primary">
            {magicValue}
          </Text>
        </Box>
        
        <Box
          flex="1"
          minWidth="250px"
          bg="sidebar"
          borderRadius={2}
          p={4}
        >
          <Box 
            display="flex" 
            justifyContent="space-between" 
            alignItems="center"
            mb={3}
          >
            <Text fontSize={2} fontWeight="bold">
              今日签到
            </Text>
            <Button 
              onClick={handleDailyCheckIn} 
              disabled={hasCheckedInToday()}
            >
              {hasCheckedInToday() ? "已签到" : "签到"}
            </Button>
          </Box>
          
          <Box
            display="flex"
            alignItems="center"
            mb={3}
          >
            <Text fontSize={1} mr={2}>
              本月签到进度:
            </Text>
            <Text fontSize={2} fontWeight="bold" color="primary">
              {checkinStatus.completed}
            </Text>
            <Text fontSize={1} mx={1}>
              /
            </Text>
            <Text fontSize={2}>
              {checkinStatus.total}
            </Text>
          </Box>
          
          <Box 
            width="100%" 
            height="6px" 
            bg="#eee" 
            borderRadius="3px" 
            overflow="hidden"
            mb={3}
          >
            <Box 
              width={`${(checkinStatus.completed / checkinStatus.total) * 100}%`} 
              height="100%" 
              bg="primary"
            />
          </Box>
          
          {checkinStatus.isComplete && !checkinStatus.bonusClaimed && (
            <Box textAlign="center" mt={3}>
              <Text color="success" mb={2}>
                恭喜达成本月全勤！
              </Text>
              <Button onClick={claimMonthlyBonus}>
                领取500点奖励
              </Button>
            </Box>
          )}
          
          {checkinStatus.isComplete && checkinStatus.bonusClaimed && (
            <Box textAlign="center" mt={3}>
              <Text color="success">
                已领取本月全勤奖励
              </Text>
            </Box>
          )}
        </Box>
      </Box>
      
      <Box 
        bg="sidebar" 
        borderRadius={2}
        p={4}
        mb={5}
      >
        <Text fontSize={2} fontWeight="bold" mb={3}>
          本月签到日历
        </Text>
        {renderCalendar()}
      </Box>
      
      <Text as="h2" mb={4}>
        魔力值获取与消耗规则
      </Text>
      <Box as="ul" mb={5}>
        <Text as="li">
          每日签到可获得 <strong>50</strong> 点魔力值
        </Text>
        <Text as="li">
          每次评分可获得 <strong>10</strong> 点魔力值（每个资源只能获取一次）
        </Text>
        <Text as="li">
          每月完整签到可额外获得 <strong>500</strong> 点魔力值奖励
        </Text>
        <Text as="li">兑换奖励会消耗相应魔力值</Text>
      </Box>
      
      <Text as="h2" mb={4}>
        魔力值历史记录
      </Text>
      {history.length > 0 ? (
        <List
          data={history}
          columns={[
            {
              header: "类型",
              accessor: "type",
              cell: ({ value }) =>
                value === "gain" ? (
                  <Text color="success">获得</Text>
                ) : (
                  <Text color="error">消耗</Text>
                ),
              gridWidth: "100px",
            },
            {
              header: "数量",
              accessor: "amount",
              cell: ({ value, row }) => (
                <Text color={row.type === "gain" ? "success" : "error"}>
                  {row.type === "gain" ? "+" : "-"}
                  {value}
                </Text>
              ),
              gridWidth: "80px",
            },
            {
              header: "原因",
              accessor: "reason",
              cell: ({ value }) => <Text>{value}</Text>,
              gridWidth: "2fr",
            },
            {
              header: "时间",
              accessor: "date",
              cell: ({ value }) => <Text>{value}</Text>,
              gridWidth: "1.5fr",
            },
          ]}
          mb={5}
        />
      ) : (
        <Box p={4} bg="sidebar" borderRadius={2}>
          <Text color="grey">暂无历史记录</Text>
        </Box>
      )}
    </>
  );
};

export default Magic;
